package com.zhu.controller.admin;

import com.zhu.base.http.RestResponse;
import com.zhu.base.util.WeekDateUtil;
import com.zhu.domain.*;
import com.zhu.domain.enums.OperationEnum;
import com.zhu.domain.enums.PropTypeEnum;
import com.zhu.model.admin.GetAllInventoryRecordItemVM;
import com.zhu.model.admin.GetAllInventoryRecordVM;
import com.zhu.model.admin.TableColumnVM;
import com.zhu.model.inventoryRecord.InventoryRecordConditionSelectVM;
import com.zhu.model.inventoryRecord.InventoryRecordUpdateVM;
import com.zhu.model.inventoryRecordItem.InventoryRecordItemDeleteVM;
import com.zhu.model.inventoryRecordItem.InventoryRecordItemInsertVM;
import com.zhu.model.inventoryRecordItem.InventoryRecordItemSelectVM;
import com.zhu.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author JoyBoyZH
 * @description 库存记录管理
 * @date 2022/6/3
 */
@CrossOrigin
@RestController
@RequestMapping(value = "/gim/api/admin/manageInventoryRecord")
@Api(tags = "管理员库存记录模块说明")
public class AdminInventoryRecordController {
    private final ModelMapper modelMapper;
    private final WarehouseService warehouseService;
    private final InventoryService inventoryService;
    private final InventoryRecordService inventoryRecordService;
    private final InventoryRecordItemService inventoryRecordItemService;
    private final TableColumnService tableColumnService;

    @Autowired
    public AdminInventoryRecordController(ModelMapper modelMapper, WarehouseService warehouseService, InventoryService inventoryService, InventoryRecordService inventoryRecordService, InventoryRecordItemService inventoryRecordItemService, TableColumnService tableColumnService) {
        this.modelMapper = modelMapper;
        this.warehouseService = warehouseService;
        this.inventoryService = inventoryService;
        this.inventoryRecordService = inventoryRecordService;
        this.inventoryRecordItemService = inventoryRecordItemService;
        this.tableColumnService = tableColumnService;
    }


    @PostMapping(value = "/selectInventoryRecord")
    @Transactional(rollbackFor = Exception.class)
    @ApiOperation("查询出入库记录说明")
    public RestResponse<Object> selectInventoryRecord(@RequestBody InventoryRecordConditionSelectVM model) {
        boolean bool = model.getWarehouseName() == null && model.getRid() == null && model.getMinTime() == null && model.getMaxTime() == null;
        List<InventoryRecord> list;
        if (bool) {
            list = inventoryRecordService.getInventoryRecordByOperation(model.getOperation());
        } else {
            list = inventoryRecordService.conditionSelect(model.getOperation(), model.getWarehouseName(), model.getRid());
        }

        if (list.isEmpty()) {
            return RestResponse.failure("不存在满足条件的记录");
        } else if (bool) {
            return RestResponse.ok(list);
        } else {
            List<InventoryRecord> listInfo = new ArrayList<>();
            Date minTime = model.getMinTime();
            Date maxTime = model.getMaxTime();
            for (InventoryRecord record : list) {
                Date time = record.getTime();
                if (minTime != null && maxTime != null) {
                    if (time.getTime() >= minTime.getTime() && time.getTime() <= maxTime.getTime()) {
                        listInfo.add(record);
                    }
                } else {
                    if (minTime != null && time.getTime() >= minTime.getTime()) {
                        listInfo.add(record);
                    }
                    if (maxTime != null && time.getTime() <= maxTime.getTime()) {
                        listInfo.add(record);
                    }
                }
            }
            if (listInfo.isEmpty()) {
                listInfo = list;
            }
            List<TableColumn> tableColumn = null;
            GetAllInventoryRecordVM modelInfo = new GetAllInventoryRecordVM();
            if (model.getOperation() == 0) {
                tableColumn = tableColumnService.getList(PropTypeEnum.OUTRECORD.getCode());
            } else if (model.getOperation() == 1) {
                tableColumn = tableColumnService.getList(PropTypeEnum.INPUTRECORD.getCode());
            }
            List<TableColumnVM> tableColumnVMList = new ArrayList<>();
            for (TableColumn tc : tableColumn) {
                TableColumnVM tableColumnVM = new TableColumnVM();
                tableColumnVM.setProp(tc.getProp());
                tableColumnVM.setPropName(tc.getPropName());
                tableColumnVMList.add(tableColumnVM);
            }
            modelInfo.setTableColumnList(tableColumnVMList);
            modelInfo.setInventoryRecordList(listInfo);
            modelInfo.setTotalNum(listInfo.size());
            return RestResponse.ok(modelInfo);
        }
    }


    @PostMapping(value = "/selectRecordItem/{recordId}")
    @Transactional(rollbackFor = Exception.class)
    @ApiOperation("查询库存记录详情说明")
    public RestResponse<Object> selectRecordItem(@PathVariable Integer recordId) {
        GetAllInventoryRecordItemVM modelInfo = new GetAllInventoryRecordItemVM();
        List<TableColumn> tableColumn = tableColumnService.getList(PropTypeEnum.RECORDITEM.getCode());
        List<TableColumnVM> tableColumnVMList = new ArrayList<>();
        for (TableColumn tc : tableColumn) {
            TableColumnVM tableColumnVM = new TableColumnVM();
            tableColumnVM.setProp(tc.getProp());
            tableColumnVM.setPropName(tc.getPropName());
            tableColumnVMList.add(tableColumnVM);
        }
        List<InventoryRecordItemSelectVM> list = inventoryRecordItemService.getByRelevance(recordId);
        modelInfo.setTableColumnList(tableColumnVMList);
        modelInfo.setInventoryRecordItemList(list);
        modelInfo.setTotalNum(list.size());
        return RestResponse.ok(modelInfo);
    }

    @GetMapping(value = "/selectRecordDate")
    @Transactional(rollbackFor = Exception.class)
    @ApiOperation("查询库存记录日期分布")
    public RestResponse<Object> selectRecordDate() {
        List<InventoryRecord> outRecordList = inventoryRecordService.getInventoryRecordByOperation(OperationEnum.OUT.getCode());
        List<InventoryRecord> inputRecordList = inventoryRecordService.getInventoryRecordByOperation(OperationEnum.INPUT.getCode());
        List<Integer[]> list = new ArrayList<>();
        Integer[] inputArray = {0, 0, 0, 0, 0, 0, 0};
        Integer[] outArray = {0, 0, 0, 0, 0, 0, 0};
        List<String> lastWeekDayList = WeekDateUtil.getLastWeekDayList();

        for (InventoryRecord inventoryRecord1 : outRecordList) {
            Date date1 = inventoryRecord1.getTime();
            SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
//            sdf1.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
            String dateStr1 = sdf1.format(date1);
            for (int i = 0; i < lastWeekDayList.size(); i++) {
                if (lastWeekDayList.get(i).equals(dateStr1)) {
                    outArray[i] += 1;
                }
            }
        }
        for (InventoryRecord inventoryRecord2 : inputRecordList) {
            Date date2 = inventoryRecord2.getTime();
            SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd");
            String dateStr2 = sdf2.format(date2);
//            System.out.println("dateStr2  "+dateStr2);
            for (int i = 0; i < lastWeekDayList.size(); i++) {
//                System.out.println("date "+lastWeekDayList.get(i));
                if (lastWeekDayList.get(i).equals(dateStr2)) {
                    inputArray[i] += 1;
                }
            }
        }
        list.add(outArray);
        list.add(inputArray);
        return RestResponse.ok(list);
    }

    @PostMapping(value = "/addRecordItem")
    @Transactional(rollbackFor = Exception.class)
    @ApiOperation("添加库存记录详情说明")
    public RestResponse<Object> addRecordItem(@RequestBody InventoryRecordItemInsertVM model) {
        Warehouse warehouse = warehouseService.getByName(model.getWarehouseName());
        int num;
        if (model.getOperation().equals(OperationEnum.INPUT.getCode())) {
            num = warehouse.getTotalInventory() + model.getNumber();
            if (num > warehouse.getCapacity()) {
                return RestResponse.failure("仓库容量不足！");
            } else {
                warehouse.setTotalInventory(num);
                warehouseService.updateWarehouse(warehouse);
            }
        } else if (model.getOperation().equals(OperationEnum.OUT.getCode())) {
            num = warehouse.getTotalInventory() - model.getNumber();
            warehouse.setTotalInventory(num);
            warehouseService.updateWarehouse(warehouse);
        }

        Inventory inventory = new Inventory();
        inventory.setWarehouseId(warehouse.getWarehouseId());
        inventory.setGoodsId(model.getGoodsId());
        inventory.setNumber(model.getNumber());
        InventoryRecordItem inventoryRecordItem = new InventoryRecordItem();
        inventoryRecordItem.setRecordId(model.getRecordId());
        inventoryRecordItem.setGoodsId(model.getGoodsId());
        inventoryRecordItem.setNumber(model.getNumber());

        if (!inventoryService.saveInventory(inventory)) {
            return RestResponse.failure("库存添加失败");
        }
        if (!inventoryRecordItemService.saveInventoryRecordItem(inventoryRecordItem)) {
            return RestResponse.failure("库存记录添加失败");
        }
        return RestResponse.ok("添加成功！");
    }

    @PostMapping(value = "/deleteRecordItem")
    @Transactional(rollbackFor = Exception.class)
    @ApiOperation("删除库存记录详情说明")
    public RestResponse<Object> deleteRecordItem(@RequestBody InventoryRecordItemDeleteVM model) {
        Warehouse warehouse = warehouseService.getByName(model.getWarehouseName());
        int num;
        if (model.getOperation().equals(OperationEnum.INPUT.getCode())) {
            num = warehouse.getTotalInventory() - model.getNumber();
            if (num > warehouse.getCapacity()) {
                return RestResponse.failure("仓库容量不足！");
            } else {
                warehouse.setTotalInventory(num);
                warehouseService.updateWarehouse(warehouse);
            }
        } else if (model.getOperation().equals(OperationEnum.OUT.getCode())) {
            num = warehouse.getTotalInventory() + model.getNumber();
            warehouse.setTotalInventory(num);
            warehouseService.updateWarehouse(warehouse);
        }
        Inventory inventory = inventoryService.getInventoryByCondition(warehouse.getWarehouseId(), model.getGoodsId());

        if (!inventoryService.deleteById(inventory.getInventoryId())) {
            return RestResponse.failure("库存删除失败");
        }

        if (!inventoryRecordItemService.deleteRecordItem(model.getRecordItemId())) {
            return RestResponse.failure("库存记录详情删除失败");
        }
        return RestResponse.ok("删除库存记录详情成功！");
    }

    @PostMapping(value = "/updateRecordItem")
    @Transactional(rollbackFor = Exception.class)
    @ApiOperation("修改库存记录详情说明")
    public RestResponse<Object> updateRecordItem(@RequestBody InventoryRecordItemDeleteVM model) {
        Warehouse warehouse = warehouseService.getByName(model.getWarehouseName());
        InventoryRecordItem inventoryRecordItem = inventoryRecordItemService.getByInventoryRecordItemId(model.getRecordItemId());
        int numInfo = inventoryRecordItem.getNumber() - model.getNumber();
        int num;
        if (model.getOperation().equals(OperationEnum.INPUT.getCode())) {
            num = warehouse.getTotalInventory() - numInfo;
            if (num > warehouse.getCapacity()) {
                return RestResponse.failure("仓库容量不足！");
            } else {
                warehouse.setTotalInventory(num);
                warehouseService.updateWarehouse(warehouse);
            }
        } else if (model.getOperation().equals(OperationEnum.OUT.getCode())) {
            num = warehouse.getTotalInventory() + numInfo;
            warehouse.setTotalInventory(num);
            warehouseService.updateWarehouse(warehouse);
        }
        Inventory inventory = inventoryService.getInventoryByCondition(warehouse.getWarehouseId(), model.getGoodsId());
        inventory.setNumber(model.getNumber());
        if (!inventoryService.updateInventory(inventory)) {
            return RestResponse.failure("库存修改失败");
        }
        inventoryRecordItem.setNumber(model.getNumber());
        if (!inventoryRecordItemService.updateInventoryRecordItem(inventoryRecordItem)) {
            return RestResponse.failure("库存记录详情修改失败");
        }
        return RestResponse.ok("修改库存记录详情成功！");
    }


    @PostMapping(value = "/updateInventoryRecord")
    @Transactional(rollbackFor = Exception.class)
    @ApiOperation("修改库存记录说明")
    public RestResponse<Object> updateRecord(@RequestBody InventoryRecordUpdateVM model) {
        InventoryRecord inventoryRecord = modelMapper.map(model, InventoryRecord.class);
        if (!inventoryRecordService.updateInventoryRecord(inventoryRecord)) {
            return RestResponse.failure("修改失败！");
        }
        return RestResponse.ok("更改成功");
//        Warehouse warehouse = warehouseService.getByName(model.getWarehouseName());
//
//        int number = 0;
//        for (InventoryVM inventoryVM : model.getInventoryVMList()) {
//            Inventory inventory = inventoryService.getInventoryByCondition(warehouse.getWarehouseId(), inventoryVM.getGoodsId());
//            int numberInfo = inventoryVM.getNumber() - inventory.getNumber();
//            number += numberInfo;
//            if (model.getOperation() == 0) {
//                inventory.setNumber(inventory.getNumber() - numberInfo);
//            } else if (model.getOperation() == 1) {
//                inventory.setNumber(inventoryVM.getNumber() + numberInfo);
//            }
//            inventoryService.updateInventory(inventory);
//        }
//
//        if (model.getOperation() == 0) {
//            warehouse.setTotalInventory(warehouse.getTotalInventory() + number);
//        } else if (model.getOperation() == 1) {
//            warehouse.setTotalInventory(warehouse.getTotalInventory() - number);
//        }
//        warehouseService.updateWarehouse(warehouse);

    }

}
